package org.example.nio;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author 邓天天
 * @date 2021/4/4 16:46
 */
public class NIOServer {
    public static void main(String[] args) throws Exception{
        //
        final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        final Selector selector = Selector.open();

        serverSocketChannel.bind(new InetSocketAddress(9999));

        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 循环等待客户端连接
        while (selector.select()>0) {
            final Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                final SelectionKey selectionKey = iterator.next();

                if (selectionKey.isAcceptable()) {
                    System.out.println("当前有连接就绪了");
                    final SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_READ);

                }
                else if (selectionKey.isReadable()) {
                    System.out.println("当前有连接可读了");
                   SocketChannel channel = (SocketChannel) selectionKey.channel();
                    final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                   int read = 0;
                   while ((read = channel.read(byteBuffer)) > 0) {
                       byteBuffer.flip();
                       System.out.println("from 客户端"+new String(byteBuffer.array(),0,read));
                       byteBuffer.clear();
                   }
                }
                // 移除，房子重复消费
                iterator.remove();
             }

        }
        selector.close();
        serverSocketChannel.close();
    }
}
